<template>
	<div>
		<el-row :gutter="20" v-if="isCreate || storeinfo" type="flex" justify="center">
			<el-col :span="15" class="left">
			  <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
			    <!-- 店铺宣传照 -->
			    <el-form-item label="店铺宣传照" prop="store_banner">
			      <el-upload
			      :action="api_upload"
						:multiple="true"
			      :on-preview="handlePreview" 
			      :on-remove="handleRemove" 
			      list-type="picture"
						:file-list="fileList"
			      :on-success="handleSuccess">
			        <el-button size="small" type="primary">点击上传</el-button>
			      </el-upload>
			    </el-form-item>
			  	<!-- 店铺名称 -->
			  	<el-form-item label="店铺名称" prop="store_name">
			  	  <el-input v-model="addForm.store_name" ref="storeNameRef" :disabled="disabled"></el-input>
			  	</el-form-item>
			    <!-- 店铺简介 -->
			    <el-form-item label="店铺简介" prop="store_intro">
						<el-input v-model="addForm.store_intro" type="textarea" rows="10"></el-input>
			    </el-form-item>
					<!-- 店铺联系电话 -->
					<el-form-item label="联系电话" prop="phone">
					  <el-input v-model="addForm.phone" ></el-input>
					</el-form-item>
			    <!-- 店铺地址 -->
			    <el-form-item label="店铺地址" prop="address2">
						<el-cascader ref="cascader" v-model="addressForm.address1" :options="cityData" :props="addressProps" clearable @change="hideCascader" style="width: 100%;"></el-cascader>
						<el-input v-model="addressForm.address2" class="address"></el-input>
			    </el-form-item>
			  	<!-- 商家 发货地址 -->
			  	<el-form-item label="发货地址" prop="address4">
						<el-cascader ref="cascader" v-model="addressForm.address3" :options="cityData" :props="addressProps" clearable @change="hideCascader" style="width: 100%;"></el-cascader>
						<el-input v-model="addressForm.address4" class="address"></el-input>
			  	</el-form-item>
					 <el-form-item>
					    <el-button type="primary" @click="submitForm()">{{ storeinfo ? '保存修改' : '立即创建'}}</el-button>
					  </el-form-item>
			  </el-form>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	import cityData from '../order/citydata.js'
	export default {
		props:[ 'storeinfo', 'isCreate' ],
		inject:['reload'],
		data() {
			// 验证手机号码的规则
			var checkMobile = (rule, value, callback) => {
			  // 验证手机号的正则表达式
			  const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
			  if (regMobile.test(value)) {
			    // 合法的邮箱
			    return callback()
			  }
			  callback(new Error('请输入合法的手机号'))
			}
			return{
				api_url: this.$api_url,
				api_upload: this.$api_upload,
				previewPath: '',
				disabled: false,
				// 添加和修改店铺的表单数据
				addForm: {
					store_banner: [],
					store_name: '',
					store_intro: '',
					phone: '',
					address: [],
					send_address: [],
					store_belong: ''
				},
				// 添加地址表单
				addressForm: {
					// 店铺地址
				  address1: [],
				  address2: '',
					// 发货地址
					address3: [],
					address4: ''
				},
				cityData: cityData,
				// 指定级联选择器的配置对象
				addressProps: {
				  expandTrigger: true,
				  checkStrictly: true
				},
				// 添加表单的验证规则对象
				addFormRules: {
					store_banner: [{
					  required: true,
					  message: '请选择店铺宣传照',
					  trigger: 'blur'
					}],
				  store_name: [{
				    required: true,
				    message: '请输入店铺名称',
				    trigger: 'blur'
				  },
				  {
				    min: 5,
				    max: 20,
				    message: '用户名的长度在 5 到 20 个字符',
				    trigger: 'blur'
				  }
				  ],
				  store_intro: [{
				    required: true,
				    message: '请输入店铺简介',
				    trigger: 'blur'
				  },
				  {
				    min: 50,
				    max: 400,
				    message: '简介的长度在 50 到 400 个字符',
				    trigger: 'blur'
				  }
				  ],
				  phone: [{
				    required: true,
				    message: '请输入联系电话',
				    trigger: 'blur'
				  },
				  {
				    validator: checkMobile,
				    trigger: 'blur'
				  }
				  ],
					address: [{
					  required: true,
					  message: '请选择店铺地址',
					  trigger: 'blur'
					}
					],
					send_address: [{
					  required: true,
					  message: '请选择发货地址',
					  trigger: 'blur'
					}]
				},
				// 修改表单的验证规则对象
				addressFormRules: {
				  address1: [
				    { required: true, message: '请选择省市区县', trigger: 'blur' }
				  ],
				  address2: [
				    { required: true, message: '请填写店铺详细地址', trigger: 'blur' }
				  ],
					address3: [
					  { required: true, message: '请选择省市区县', trigger: 'blur' }
					],
					address4: [
					  { required: true, message: '请填写发货详细地址', trigger: 'blur' }
					]
				},
				fileList: [],
				userinfo: {}
			}
		},
		created() {
			this.userinfo = JSON.parse(window.sessionStorage.getItem('userinfo'));
		},
		mounted() {
			if (this.storeinfo) {
				this.addForm = this.storeinfo;
				this.addressForm.address1 = this.addForm.address[0].split(',');
				this.addressForm.address2 = this.addForm.address[1];
				this.addressForm.address3 = this.addForm.send_address[0].split(',');
				this.addressForm.address4 = this.addForm.send_address[1];
				this.addForm.store_banner.forEach((item)=>{
					this.fileList.push({
						url: this.api_url + item
					})
				})
				this.disabled = true;
			}
			
		},
		methods:{
			// 处理图片预览效果
			handlePreview (file) {
			  console.log(file)
			  this.previewPath = file.response.data.url
			  console.log(previewPath)
			  this.previewVisible = true
			},
			// 处理移除图片的操作
			handleRemove (file) {
			  console.log(file)
				let filePath;
				if (file.response) {
					// 1.获取将要删除的图片的临时路径
					filePath = file.response[0].file;
				} else {
					// 1.获取将要删除的图片的临时路径
					filePath = file.url.split(this.api_url)[1];
				}
				// 2.从pics数组中,找到这图片对应的索引值
				const index = this.addForm.store_banner.findIndex(x => x === filePath);
				// 3.调用数组的splice方法,把图片信息对象从pics数组中移除
				this.addForm.store_banner.splice(index, 1)
				console.log('img',this.addForm.store_banner)
			},
			// 监听图片上传成功的事件
			handleSuccess (res) {
			  console.log(res)
			  // 1.拼接得到一个图片信息对象
			  // 2.将图片信息对象 push 到pics数组中
			  this.addForm.store_banner.push( '\\' + res[0].file)
			  console.log(this.addForm.store_banner)
			},
			hideCascader () {
			  this.$refs.cascader.dropDownVisible = false;
				console.log(this.addressForm.address1);
			},
			// 创建店铺
			submitForm () {
				this.addForm.store_belong = this.userinfo._id;
				this.addForm.address = [this.addressForm.address1.join(','),this.addressForm.address2];
				this.addForm.send_address = [this.addressForm.address3.join(','),this.addressForm.address4];
				console.log(this.addForm);
				// return
			  this.$refs.addFormRef.validate(async valid => {
			    if (!valid) return
			    // 发起创建店铺信息的数据请求
					let res;
					if (!this.storeinfo) {
						res = await this.$http.post('stores', this.addForm)
					} else {
						res = await this.$http.put('stores', this.addForm)
					}
					console.log(res);
			    if (res.data.code !== 200) return this.$message.error(res.data.msg)
					this.$message.success(res.data.msg)
					// 刷新数据列表
					this.reload();
					// this.$emit('refresh');
			    
			  })
			},
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .el-upload-list__item {
		width: 100px; 
		float: left;
		margin-right: 10px;
	}
	
	// .left {
	// 	border: 2px solid #eee;
	// 	border-radius: 5px;
	// 	padding:  10px 0;
	// }
	.address {
		margin-top: 20px;
	}
</style>
